package com.example.myvideo.View;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.myvideo.R;
import com.example.myvideo.View.impl.AuthModelImpl;
import com.example.myvideo.View.impl.AuthPresenterImpl;
import com.example.myvideo.contract.AuthView;
import com.example.myvideo.database.DBHelper;
import com.example.myvideo.entity.User;
import com.example.myvideo.model.AuthModel;
import com.example.myvideo.presenter.AuthPresenter;


import java.io.File;
import java.io.InputStream;

public class RegisterActivity extends AppCompatActivity implements AuthView {
    private static final int REQUEST_PERMISSION = 1;
    private static final int REQUEST_IMAGE_CAPTURE = 2;
    private EditText etUsername, etPassword;
    private ImageView ivAvatar;
    private Button btnRegister;
    private AuthPresenter presenter;
    private String avatarPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        ivAvatar = findViewById(R.id.etImage);
        btnRegister = findViewById(R.id.btnregister);

        DBHelper dbHelper = new DBHelper(this);
        AuthModel model = new AuthModelImpl(this, dbHelper);
        presenter = new AuthPresenterImpl(this, model, dbHelper);

        ivAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(RegisterActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION);
                } else {
                    openFileChooser();
                }
            }
        });

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = etUsername.getText().toString();
                String password = etPassword.getText().toString().trim();
                Log.d("RegisterActivity", "Username (before trim): " + username); // 添加日志输出
                username = username.trim();
                Log.d("RegisterActivity", "Username (after trim): " + username); // 添加日志输出

                if (username.isEmpty() || password.isEmpty() || avatarPath == null) {
                    if (username.isEmpty()) {
                        showUsernameError();
                    } else if (password.isEmpty()) {
                        showPasswordError();
                    } else {
                        showErrorMessage("Please select an avatar.");
                    }
                } else {
                    presenter.register(username, password, avatarPath);
                }
            }
        });
    }

    private void openFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_IMAGE_CAPTURE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openFileChooser();
            } else {
                Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Uri selectedImage = data.getData();
            if (selectedImage != null) {
                try {
                    InputStream inputStream = getContentResolver().openInputStream(selectedImage);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    ivAvatar.setImageBitmap(bitmap);
                    // Save the image to the app directory
                    avatarPath = saveImageToAppDirectory(bitmap);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(this, "Error occurred while selecting the image.", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private String saveImageToAppDirectory(Bitmap bitmapImage) {
        // Save the bitmap to the app directory and return the path
        // Implement this method to save the image and return the path
        return "path_to_image";
    }

    // AuthView methods
    @Override
    public void showLoading() {
        // Show a loading indicator
    }

    @Override
    public void hideLoading() {
        // Hide the loading indicator
    }

    @Override
    public void showErrorMessage(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void navigateToHomeScreen() {
        // Navigate to the home screen of the app
    }

    @Override
    public void showUsernameError() {
        etUsername.setError("Username is required.");
    }

    @Override
    public void showPasswordError() {
        etPassword.setError("Password is required.");
    }

    @Override
    public void showRegistrationSuccess() {
        Toast.makeText(this, "Registration successful!", Toast.LENGTH_SHORT).show();
    }
}